import { message } from 'ant-design-vue'

declare global {
  interface Window {
    [index: string]: any
  }
}
interface Query {
  url: string
  customFncName?: string
  cbName?: string
}
const jspRequest = (query: Query) => {
  return new Promise(resolve => {
    const script = document.createElement('script')
    const functionName =
      query.customFncName ?? 'RequestCB' + new Date().getTime()

    const firstKey = functionName.split('.').shift() as string

    window[firstKey] = createWindowCB(functionName, resolve)[firstKey]

    script.src = `${query.url}&${query.cbName ?? 'cb'}=window.${functionName}`

    document.body.appendChild(script)
    script.onload = function () {
      document.body.removeChild(script)
      delete window[firstKey]
    }
    script.onerror = function () {
      message.error('请求错误')
      document.body.removeChild(script)
      delete window[firstKey]
    }
  })
}

const createWindowCB = (cbName: string, resolve: (value: unknown) => void) => {
  const list = cbName.split('.')

  const createObjByCBName = (list: string[]) => {
    let result: Record<string, any> | (() => void)

    if (!list.length) {
      result = function (response: any) {
        resolve(response)
      }
    } else {
      const currentKey = list.shift() as string
      result = {}
      result[currentKey] = createObjByCBName(list)
    }

    return result
  }

  return createObjByCBName(list)
}

export default jspRequest
